import React, { useState } from 'react';
import { Text, View, TextInput, ToastAndroid , Image, ScrollView, StyleSheet, Alert, SafeAreaView, TouchableOpacity, useColorScheme } from 'react-native';
import { useSelector } from 'react-redux';
import { launchImageLibrary } from 'react-native-image-picker';
import { request, PERMISSIONS, RESULTS } from 'react-native-permissions';
import { Platform } from 'react-native';
import { RootState } from '../Store/store.ts';

// 定义 ImagePicker 响应资产类型
type ImagePickerAsset = {
  uri: string;
  type: string;
  fileName: string;
  fileSize?: number;
};

interface PostObject{
  noteId: number;
  hasVideo: boolean;
  video?: string; // Base64 编码的视频数据
  images?: string[]; // Base64 编码的图片数据数组
  title: string;
  content: string;
  authorId: string;
}

// 服务器 API 地址
const API_URL = 'https://your-api-url.com';

// 最大视频大小（可配置），单位：字节
const MAX_VIDEO_SIZE = 100 * 1024 * 1024; // 100MB

function PublishScreen() {
  const colorScheme = useColorScheme();
  const isDarkMode = colorScheme === 'dark';
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const [images, setImages] = useState<ImagePickerAsset[]>([]);
  const [video, setVideo] = useState<ImagePickerAsset | null>(null);
  const token: string = useSelector((state: RootState) => state.loginState.userInfo.token);

  // 请求相册和相机权限
  const requestPermissions = async () => {
    let photoPermission;
    let videoPermission;

    if (Platform.OS === 'android') {
      photoPermission = await request(PERMISSIONS.ANDROID.READ_EXTERNAL_STORAGE);
      videoPermission = await request(PERMISSIONS.ANDROID.CAMERA);
    } else if (Platform.OS === 'ios') {
      photoPermission = await request(PERMISSIONS.IOS.PHOTO_LIBRARY);
      videoPermission = await request(PERMISSIONS.IOS.CAMERA);
    }

    if (photoPermission === RESULTS.GRANTED && videoPermission === RESULTS.GRANTED) {
      return true;
    } else {
      ToastAndroid.show('请授予相册和相机权限以选择图片和视频', ToastAndroid.SHORT);
      return false;
    }
  };

  // 选择图片
  const selectImages = async () => {
    if (images.length >= 9) {
      ToastAndroid.show('最多只能选择 9 张图片', ToastAndroid.SHORT);
      return;
    }

    const hasPermissions = await requestPermissions();
    if (!hasPermissions) return;

    try {
      const options = {
        title: '选择图片',
        storageOptions: {
          skipBackup: true,
          path: 'images',
        },
        mediaType: 'photo',
        maxWidth: 1000,
        maxHeight: 1000,
        quality: 0.8,
        selectionLimit: 9 - images.length,
      };

      await launchImageLibrary(options, (response: {
        didCancel: boolean;
        error?: string;
        assets?: ImagePickerAsset[]
      }) => {
        if (response.didCancel) {
          console.log('用户取消选择图片');
        } else if (response.error) {
          console.error('选择图片时出错:', response.error);
          Alert.alert('错误', '选择图片时出错，请稍后重试');
        } else if (response.assets) {
          const newImages = [...images, ...response.assets];
          if (newImages.length > 9) {
            setImages(newImages.slice(0, 9));
            Alert.alert('提示', '已达到图片数量上限，仅保留前 9 张图片');
          } else {
            setImages(newImages);
          }
        }
      });
    } catch (error) {
      console.error('启动图片选择器时出错:', error);
      Alert.alert('错误', '启动图片选择器时出错，请稍后重试');
    }
  };

  // 选择视频
  const selectVideo = async () => {
    const hasPermissions = await requestPermissions();
    if (!hasPermissions) return;

    const options = {
      title: '选择视频',
      storageOptions: {
        skipBackup: true,
        path: 'videos',
      },
      mediaType: 'video',
    };

    await launchImageLibrary(options, (response: {
      didCancel: boolean;
      error?: string;
      assets?: ImagePickerAsset[]
    }) => {
      if (response.didCancel) {
        console.log('用户取消选择视频');
      } else if (response.error) {
        console.log('选择视频时出错:', response.error);
      } else if (response.assets && response.assets[0]?.fileSize && response.assets[0].fileSize > MAX_VIDEO_SIZE) {
        Alert.alert('视频过大', '请选择小于 100MB 的视频');
      } else if (response.assets) {
        setVideo(response.assets[0]);
      }
    });
  };

  // 验证表单数据
  const validateForm = () => {
    if (title.length < 3 || title.length > 15) {
      ToastAndroid.show('标题长度必须在 3 到 15 个字之间', ToastAndroid.SHORT);
      return false;
    }
    if (content.length < 5 || content.length > 1500) {
      ToastAndroid.show('正文长度必须在 5 到 1500 个字之间', ToastAndroid.SHORT);
      return false;
    }
    if (images.length === 0 && !video) {
      ToastAndroid.show('至少需要一张图片或一个视频', ToastAndroid.SHORT);
      return false;
    }
    return true;
  };

  // 提交笔记到服务器
  const submitNote = async () => {
    if (!validateForm()) return;

    // 创建 PostObject 对象
    // 将视频和图片转为Base64编码
    const postObject: PostObject = {
      noteId: 0,
      hasVideo: !!video,
      video: video ? `data:${video.type};base64,${video.uri}` : undefined,
      images: images.map(image => `data:${image.type};base64,${image.uri}`),
      title,
      content,
      authorId: token,
    };
    // 发送 POST 请求
    try {
      const response = await fetch(`${API_URL}/notes`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify(postObject),
      });

      if (response.ok) {
        ToastAndroid.show('笔记发布成功', ToastAndroid.SHORT);
        // 清空表单
        setTitle('');
        setContent('');
        setImages([]);
        setVideo(null);
      } else {
        const errorResponse = await response.json();
        console.error('发布笔记失败:', errorResponse);
        Alert.alert('错误', '发布笔记失败，请稍后重试');
      }
    } catch (error) {
      console.error('网络请求失败:', error);
      Alert.alert('错误', '网络请求失败，请稍后重试');
    }
  };

  const getThemeColors = () => {
    return isDarkMode
      ? {
          background: '#121212',
          textPrimary: '#FFFFFF',
          textSecondary: '#AAAAAA',
          card: '#1E1E1E',
          border: '#333333',
          button: '#007AFF',
        }
      : {
          background: '#f5f5f5',
          textPrimary: '#333333',
          textSecondary: '#666666',
          card: '#FFFFFF',
          border: '#e0e0e0',
          button: '#007AFF',
        };
  };

  const { background, textPrimary, textSecondary, card, border, button } = getThemeColors();

  return (
    <SafeAreaView style={[styles.safeAreaContainer, { backgroundColor: background }]}>
      <View style={styles.header}>
        <View style={styles.headerContent}>
          <Text style={[styles.headerTitle, { color: textPrimary }]}>发布新游记</Text>
          <TouchableOpacity style={[styles.submitButton, { backgroundColor: button }]} onPress={submitNote}>
            <Text style={styles.submitButtonText}>提交笔记</Text>
          </TouchableOpacity>
        </View>
      </View>
      <ScrollView style={styles.container}>
        <TextInput
          style={[styles.titleInput, { borderColor: border, backgroundColor: card, color: textPrimary }]}
          placeholder="标题 (3 - 15 字)"
          placeholderTextColor={textSecondary}
          value={title}
          onChangeText={setTitle}
        />
        <TextInput
          style={[styles.contentTextarea, { borderColor: border, backgroundColor: card, color: textPrimary }]}
          placeholder="正文 (5 - 1500 字)"
          placeholderTextColor={textSecondary}
          multiline
          numberOfLines={4}
          value={content}
          onChangeText={setContent}
        />
        {/* 优化图片展示区域为九宫格 */}
        <View style={styles.previewContainer}>
          {images.map((image, index) => (
            <View key={index} style={styles.imageContainer}>
              <Image source={{ uri: image.uri }} style={styles.previewImage} />
              <TouchableOpacity
                style={styles.deleteImageButton}
                onPress={() => {
                  const newImages = [...images];
                  newImages.splice(index, 1);
                  setImages(newImages);
                }}
              >
                {/* 调整 X 文字的样式使其居中 */}
                <Text style={styles.deleteImageButtonText}>×</Text>
              </TouchableOpacity>
            </View>
          ))}
        </View>
        {video && (
          <View style={[styles.videoContainer, { backgroundColor: card }]}>
            <Text style={[styles.previewVideoText, { color: textPrimary }]}>已选择视频: {video.fileName}</Text>
            <TouchableOpacity
              style={styles.deleteVideoButton}
              onPress={() => {
                setVideo(null);
              }}
            >
              <Text style={styles.deleteVideoButtonText}>×</Text>
            </TouchableOpacity>
          </View>
        )}
      </ScrollView>
      <View style={[styles.bottomContainer, { backgroundColor: card, borderTopColor: border }]}>
        <TouchableOpacity style={[styles.mediaButton, { backgroundColor: button }]} onPress={selectImages}>
          <Text style={styles.mediaButtonText}>选择图片</Text>
        </TouchableOpacity>
        <TouchableOpacity style={[styles.mediaButton, { backgroundColor: button }]} onPress={selectVideo}>
          <Text style={styles.mediaButtonText}>选择视频</Text>
        </TouchableOpacity>
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safeAreaContainer: {
    flex: 1,
  },
  header: {
    alignItems: 'flex-end',
    padding: 16,
    // 调整头部区域高度，让提交按钮靠下
    height: 80,
  },
  headerContent: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    width: '100%',
  },
  headerTitle: {
    marginTop: 20,
    fontSize: 28,
    fontWeight: 'bold',
  },
  submitButton: {
    width: 120,
    height: 40,
    marginTop: 20,
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 20,
    elevation: 3, // Android 阴影
    shadowColor: '#000', // iOS 阴影
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.2,
    shadowRadius: 2,
  },
  submitButtonText: {
    color: 'white',
    fontWeight: '600',
    fontSize: 16,
  },
  container: {
    flex: 1,
    padding: 16,
  },
  titleInput: {
    height: 50,
    borderWidth: 1,
    borderRadius: 8,
    padding: 12,
    marginBottom: 16,
    fontSize: 18,
  },
  contentTextarea: {
    height: 200,
    borderWidth: 1,
    borderRadius: 8,
    padding: 12,
    marginBottom: 16,
    fontSize: 16,
    textAlignVertical: 'top',
  },
  previewContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    // 去掉 justify-content，让图片从左到右排列
    // 调整负外边距来平衡图片之间的间距
    marginLeft: -5,
    marginTop: -5,
  },
  imageContainer: {
    // 计算每个图片容器的宽度，实现 3*3 布局
    width: '33.333%',
    // 增加外边距来控制图片之间的间距
    marginBottom: 5,
    paddingLeft: 5,
    paddingTop: 5,
    position: 'relative',
  },
  previewImage: {
    width: '100%',
    // 保持宽高比
    aspectRatio: 1,
    borderRadius: 8,
  },
  deleteImageButton: {
    position: 'absolute',
    top: -4,
    right: -4,
    backgroundColor: 'red',
    width: 28,
    height: 28,
    borderRadius: 14,
    justifyContent: 'center',
    alignItems: 'center',
    elevation: 3, // Android 阴影
    shadowColor: '#000', // iOS 阴影
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.2,
    shadowRadius: 2,
  },
  deleteImageButtonText: {
    color: 'white',
    fontSize: 28,
    // 调整行高让 X 居中
    lineHeight: 24,
    // 微调垂直位置
    marginTop: -5,
    // 微调水平位置
    marginLeft: 1,
  },
  videoContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    margin: 8,
    padding: 12,
    borderRadius: 8,
    elevation: 1, // Android 阴影
    shadowColor: '#000', // iOS 阴影
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.1,
    shadowRadius: 1,
  },
  previewVideoText: {
    flex: 1,
    fontSize: 16,
  },
  deleteVideoButton: {
    backgroundColor: 'red',
    width: 28,
    height: 28,
    borderRadius: 14,
    justifyContent: 'center',
    alignItems: 'center',

  },
  deleteVideoButtonText: {
    color: 'white',
    fontSize: 24,
    lineHeight: 24,
    // 微调垂直位置
    marginTop: -5,
    // 微调水平位置
    marginLeft: 1,
  },
  bottomContainer: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    padding: 16,
    borderTopWidth: 1,
  },
  mediaButton: {
    paddingVertical: 12,
    paddingHorizontal: 24,
    borderRadius: 24,
    elevation: 3, // Android 阴影
    shadowColor: '#000', // iOS 阴影
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.2,
    shadowRadius: 2,
  },
  mediaButtonText: {
    color: 'white',
    fontWeight: '600',
    fontSize: 16,
  },
});

export default PublishScreen;
